import React from 'react'
import {withRouter} from 'react-router-dom'
import {connect} from 'react-redux'
import {Button, Col, Icon, Input, Row, Select, Table} from 'antd'
import Screen from "../../../../components/Base/Screen";
import ContentWrap from "../../../../components/Base/ContentWrap";
import styles from './index.module.css';
import CommonUtil from "../../../../utils/CommonUtil";
import Api from "../../../../configs/Api";

const Option = Select.Option;

class ModelTool extends Screen {
    constructor(props) {
        super(props);

        this.state = {
            tables: ['default'],
            tableData: [],
            columns: [
                {
                    title: '表名',
                    dataIndex: 'name',
                },
                {
                    title: '操作',
                    dataIndex: '操作',
                    render: (name, record) => <a
                        onClick={this.genTables.bind(this, [record.name], this.state.tableSelected)}
                        href="javascript:;">重新生成</a>
                }
            ],
            pagination: {current: 1, pageSize: 10},
            loading: false,

            selectedCount: 0,
            selectedItems: [],
            tableSelected: 'default',
            keyword: '',
        };
    }

    async componentDidMount() {
        await this.getCollectionList();
        await this.handleTableChange(this.state.pagination);
    }

    handleTableChange = async (pagination) => {
        const pager = {...this.state.pagination};
        pager.page = pagination.current;
        pager.limit = pagination.pageSize;
        pager.current = pagination.current;

        return await this.getTables({
            ...pager
        })
    };

    rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);

            this.setState({selectedCount: selectedRows.length, selectedItems: selectedRows})
        },
        getCheckboxProps: record => ({}),
    };

    genTables = async (tables = [], name = 'default') => {
        let req = await this.request(Api.MODEL_GEN, {
            name: name, tables: JSON.stringify(tables),
        }, true);
        if (req.status !== Api.SUCCESS_CODE) return CommonUtil.toast(req.msg);
        CommonUtil.toast('生成成功');
    };

    getCollectionList = async () => {
        let req = await this.request(Api.MODEL_CONNECTION_LIST);
        if (req.status !== Api.SUCCESS_CODE) return CommonUtil.toast(req.msg);
        this.setState({tables: req.data});
    };

    getTables = async (params = {}) => {
        this.setState({loading: true});
        let args = {
            keyword: this.state.keyword,
            ...params,
        };
        let req = await this.request(Api.MODEL_DB_TABLES, args);
        this.setState({loading: false});
        if (req.status !== Api.SUCCESS_CODE) return CommonUtil.toast(req.msg);

        const pagination = {...params};
        pagination.total = req.data.records;
        this.setState({
            tableData: req.data.rows.map(t => ({name: t})),
            pagination,
        });
    };

    render() {
        return (
            <ContentWrap>
                <Row style={{backgroundColor: '#fff', padding: '20px', marginTop: '20px'}}>
                    <Col xs={24} sm={24} md={24} className={styles.formTop}>
                        <Col xs={24} sm={24} md={24} lg={8} style={{marginBottom: '24px'}}>
                            {/*<span className={styles.fontFourteen}>使用状态：</span>*/}
                            <Select defaultValue="default" style={{width: '70%'}} onSelect={(v) => {
                                console.log(v);
                                this.setState({tableSelected: v})
                            }}>
                                {
                                    this.state.tables.map((item) => (
                                        <Option key={item} value={item}>{item}</Option>
                                    ))
                                }
                            </Select>
                        </Col>
                        <Col xs={24} sm={24} md={24} lg={8} className={styles.formTopLeft}>
                            {/*<span className={styles.fontFourteen}>规则编号：</span>*/}
                            <Input onChange={e => this.setState({keyword: e.target.value})} value={this.state.keyword}
                                   onPressEnter={this.handleTableChange.bind(this, this.state.pagination)}
                                   placeholder="表名" style={{width: '70%'}}/>
                        </Col>

                        <Col xs={24} sm={24} md={24} lg={8} style={{marginBottom: '24px'}}>
                            <Button onClick={this.handleTableChange.bind(this, this.state.pagination)} type="primary"
                                    style={{marginRight: '8px'}}>查询</Button>
                            {/*<Button>重置</Button>*/}
                        </Col>
                    </Col>

                    <Col xs={24} sm={24} md={24} className={styles.mbSixteen}>
                        <Button onClick={this.genTables.bind(this, [], this.state.tableSelected)} type="primary"
                                style={{marginRight: '8px'}}><Icon type="plus"/>全部生成</Button>
                    </Col>

                    {
                        this.state.selectedCount ? (
                            <Col xs={24} sm={24} md={24} className={styles.tableAlert}>
                                <div className={styles.tableAlertDiv}>
                                    <span><Icon type="info-circle" style={{marginRight: '10px'}}/>已选择&nbsp;&nbsp;
                                        <a className={styles.clearLink}
                                           style={{fontWeight: 600}}>{this.state.selectedCount}</a>&nbsp;&nbsp;项&nbsp;&nbsp;
                                        <a onClick={this.genTables.bind(this, this.state.selectedItems.map(s => s.name), this.state.tableSelected)}
                                           className={styles.clearLink} style={{marginLeft: '24px'}}>生成已选择</a>
                                    </span>
                                </div>
                            </Col>
                        ) : null
                    }
                    <Col xs={24} sm={24} md={24}>
                        <Table rowSelection={this.rowSelection}
                               rowKey={record => record.name}
                               columns={this.state.columns}
                               dataSource={this.state.tableData}
                               pagination={this.state.pagination}
                               loading={this.state.loading}
                               onChange={this.handleTableChange.bind(this)}
                               size={'middle'}
                               bordered={true}/>
                    </Col>
                </Row>
            </ContentWrap>
        )
    }
}

export default withRouter(connect()(ModelTool))

